<template>
  <BasicModal v-bind="$attrs" @register="register" @ok="handleSubmit" :title="getTitle">
    <div class="pt-3px pr-3px">
      <BasicForm @register="registerForm" />
    </div>
  </BasicModal>
</template>
<script lang="ts">
  import { defineComponent, ref, computed, unref } from 'vue';
  import { BasicModal, useModalInner } from '/@/components/Modal';
  import { BasicForm, useForm } from '/@/components/Form/index';
  import { fromConfig } from './formData';
  import { AddModel, editeModel, getDeviceModeList } from '/@/api/sys/gateway/gateway';
  export default defineComponent({
    components: { BasicModal, BasicForm },
    props: {
      method: { type: String, defaultValue: 'add' },
      formData: { type: Object },
    },
    emits: ['success'],
    setup(_, { emit }) {
      const isUpdate = ref(true);
      const [registerForm, { setFieldsValue, resetFields, validate, updateSchema }] =
        useForm(fromConfig);

      const [register, { setModalProps, closeModal }] = useModalInner((data) => {
        resetFields();
        data && onDataReceive(data);
      });

      async function onDataReceive(data) {
        setModalProps({ confirmLoading: false });
        isUpdate.value = !!data?.isUpdate;
        const dt_list = await getDeviceModeList();
        updateSchema({ field: 'code', componentProps: { disabled: unref(isUpdate) } });
        if (unref(isUpdate)) {
          updateSchema({
            field: 'device_mode_id',
            componentProps: {
              options: dt_list.list.map((item) => {
                let obj = {
                  label: item.name,
                  value: item.id,
                };
                return obj;
              }),
            },
          });
          setFieldsValue(data.rowdata);
        }
      }
      const getTitle = computed(() => (!unref(isUpdate) ? '新增型号' : '编辑型号'));
      async function handleSubmit() {
        try {
          let brand_id = localStorage.getItem('brand_id');
          const values = await validate();
          values.brand_id = brand_id;
          setModalProps({ confirmLoading: true });
          if (unref(isUpdate)) {
            await editeModel(values);
          } else {
            await AddModel(values);
          }
          closeModal();
          emit('success', { isUpdate: unref(isUpdate) });
        } finally {
          setModalProps({ confirmLoading: false });
        }
      }
      return { register, getTitle, registerForm, handleSubmit };
    },
  });
</script>
